<template>
  <div class="component_container">
    <!-- 机构选择组件 -->
    <el-tooltip
      :content="modelValue.orgName"
      :disabled="!modelValue.orgName || modelValue.orgName.length < 10"
      placement="top"
    >
      <el-input
        :value="modelValue.orgName"
        placeholder="选择机构"
        :size="size"
        readonly
        clearable
        @click="open"
      >
        <template v-if="modelValue.orgName" #suffix>
          <circle-close class="icon clear_icon" @click="clearInfo" />
        </template>
      </el-input>
    </el-tooltip>

    <!-- 选择机构弹框 -->
    <el-dialog
      v-model="visible"
      title="选择机构"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="10vh"
      center
      width="800px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="search_bar">
          <el-input
            v-model="filterData.orgName"
            ref="orgNameRef"
            placeholder="机构名称"
            maxlength="50"
            size="small"
            class="search_box"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
            @input="debounceSearch"
          >
            <template #prepend>
              <search class="icon" @click="focusInput('orgNameRef')" />
            </template>
          </el-input>
        </div>

        <div class="table_box f_1">
          <vxe-table
            v-loading="tableLoading"
            :data="tableData"
            :sort-config="{ remote: true }"
            :radio-config="{ highlight: true }"
            :row-config="{ height: 100 }"
            ref="xTable"
            resizable
            align="center"
            border
            height="100%"
            show-overflow="tooltip"
            highlight-hover-row
            highlight-current-row
            class="xTable"
            @radio-change="handleRadioChange"
          >
            <vxe-column type="radio" width="60" fixed="left">
              <template #header>
                <div>
                  <el-button
                    type="text"
                    :disabled="!tableSelectRow"
                    @click="clearRadioRow"
                  >
                    取消
                  </el-button>
                </div>
              </template>
            </vxe-column>

            <vxe-column
              type="seq"
              title="序号"
              width="60"
              fixed="left"
            ></vxe-column>
            <TableColum :colums="tableColum">
              <template #avatar="{ props }">
                <div style="text-align: center">
                  <div
                    v-if="props.row.avatarUrl"
                    @click.stop=""
                    class="d_f j_c"
                  >
                    <el-image
                      style="width: 80px; height: 80px; border-radius: 50%"
                      :src="props.row.avatarUrl"
                      :preview-src-list="[props.row.avatarUrl]"
                      lazy
                    ></el-image>
                  </div>
                  <span v-else>无</span>
                </div>
              </template>
            </TableColum>
          </vxe-table>
        </div>
        <el-pagination
          v-model="pagenationData.current"
          :page-sizes="[500, 100, 50, 15]"
          :page-size="pagenationData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagenationData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
          style="text-align: center; margin-top: 10px"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="dialogLoading"
            size="small"
          >
            选择
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, getCurrentInstance, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import TableColum from "./TabelTemplate/TableColum.vue";
import { dealImgUrl } from "../utils/common";
import { debounce } from "lodash";

const initFilterData = () => {
  return {
    orgName: null,
    orgStatus: "1",
    // canJoin: "1",
  };
};

export default {
  name: "OrgSelect",
  components: {
    TableColum,
  },
  props: {
    size: {
      type: String,
      default: "mini",
      validator: (val) => {
        return ["mini", "small", "default", "large"].includes(val);
      },
    },
    modelValue: {
      type: Object,
      default: () => {
        return {
          id: null,
          orgName: null,
        };
      },
    },
  },
  emits: ["update:modelValue"],
  setup(props, context) {
    // ------------------ 通用属性 start --------------------
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();
    const store = useStore();
    // ------------------ 通用属性 end ----------------------

    /**
     * 计算属性
     */
    const userInfo = computed(() => store.state.user.userInfo);

    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});

    const tableState = reactive({
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        orgName: {
          title: "机构名称",
          props: { sortable: false },
        },
        orgAvatar: {
          title: "机构logo",
          props: { sortable: false },
          slotContent: "avatar",
        },
        orgDesc: {
          title: "机构描述",
          props: { sortable: false },
        },
        orgManagerName: {
          title: "机构管理员",
          props: { sortable: false },
        },
        creatorName: {
          title: "创建人",
          props: { sortable: false },
        },
        createdTime: {
          title: "创建时间",
          props: { sortable: false, width: 160 },
        },
      },
      tableSelectRow: null,
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      $api.organization
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              avatarUrl: dealImgUrl(item.orgAvatar),
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 列表单选选中
    const handleRadioChange = ({ row }) => {
      tableState.tableSelectRow = row;
    };

    // 清除列表选中
    const clearRadioRow = () => {
      tableState.tableSelectRow = null;
      tableState.xTable && tableState.xTable.clearRadioRow();
    };

    // 输入框聚焦
    const orgNameRef = ref(null);
    const focusInput = (refKey) => {
      switch (refKey) {
        case "orgNameRef":
          orgNameRef.value && orgNameRef.value.focus();
          break;
      }
    };

    // 防抖
    const debounceSearch = debounce(handleSearch, 800);

    // 保存
    const handleConfirm = () => {
      if (!tableState.tableSelectRow) {
        return ElMessage.warning("请先选择机构再点击确定");
      }
      const info = {
        id: tableState.tableSelectRow.id,
        orgName: tableState.tableSelectRow.orgName,
      };
      context.emit("update:modelValue", info);
      close();
    };

    // 打开弹框
    const open = () => {
      handleSearch();
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (dialogLoading.value) {
        return;
      }
      handleReset();
      visible.value = false;
    };

    const clearInfo = () => {
      clearRadioRow();
      const info = {
        id: null,
        orgName: null,
      };
      context.emit("update:modelValue", info);
    };

    return {
      userInfo,
      visible,
      open,
      close,
      dialogLoading,
      handleConfirm,
      filterData,
      pagenationData,
      handleSearch,
      getTableData,
      handleSizeChange,
      handleCurrentChange,
      handleRadioChange,
      clearRadioRow,
      debounceSearch,
      focusInput,
      orgNameRef,
      clearInfo,
      ...toRefs(tableState),
    };
  },
};
</script>

<style lang="less" scoped>
.component_container {
}

.dialog_container {
  height: calc(92vh - 240px);
  display: flex;
  flex-direction: column;
  .search_bar {
    margin-bottom: 15px;
    justify-content: center;
    .search_box {
      width: 80%;
    }
  }
}

.clear_icon {
  transform: translateY(2px);
  cursor: pointer;
  color: #ccc;
}
</style>
